""" 接口返回数据格式化 """
import json
from plugin.exception import MyException
from plugin.logger import MyLogger
import logging


class MyResponse:
    """ 设定接口返回的通用格式{code : xx, msg : xx, data : xx} """

    # def __init__(self, module_log: logging.Logger = None) -> None:
    #     self.logger = module_log if module_log else MyLogger.logger

    @staticmethod
    def Success(data=None):
        """
        返回成功，只用设置data字段数据
        无需实例化，调用方式MyResponse.Success()
        """
        # MyLogger.logger.debug('请求成功: {}'.format(data))
        return json.dumps(resp(0, 'SUCCESS', data).__dict__, ensure_ascii=False)

    @staticmethod
    def Error(exception: MyException, data=None):
        """
        返回失败，建议使用通用错误定义来返回，也可以使用元组，需要包含code和message
        无需实例化，调用方式MyResponse.Error()
        @param
            :exception: <tuple> 错误类型和描述，建议使用通用错误定义
            :message: <str> 自定义内容，使用默认日志对象记录错误日志用，方便调试
        """
        # MyLogger.logger.error('外部请求错误: {}'.format(exception))
        return json.dumps(resp(*exception, data=data).__dict__, ensure_ascii=False)


class resp:
    """ 返回类定义 """

    def __init__(self, code, message, data=None) -> None:
        self.code = code
        self.msg = message
        self.data = data


def get_param(request, param_name: str):
    """
    获取请求参数的一个通用方法
    @param
        :request: <request> 请求对象
        :param_name: <str> 参数名
    """
    comment = None
    if request.content_type.startswith('application/json'):
        comment = request.json.get(param_name)
    elif request.content_type.startswith('multipart/form-data'):
        comment = request.form.get(param_name)
    else:
        if request.method == "GET":
            comment = request.args.get(param_name)
        if request.method == "POST":
            comment = request.values.get(param_name)
    return comment


def get_param(request, param_name: list):
    """
    获取请求参数的一个通用方法
    @param
        :request: <request> 请求对象
        :param_name: <str> 参数名列表
    """
    comment = []
    if request.content_type.startswith('application/json'):
        comment = [request.json.get(i) for i in param_name]
    elif request.content_type.startswith('multipart/form-data'):
        comment = [request.form.get(i) for i in param_name]
    else:
        if request.method == "GET":
            comment = [request.args.get(i) for i in param_name]
        if request.method == "POST":
            comment = [request.values.get(i) for i in param_name]
    return tuple(comment)